// 设置预览组件
// 为设置更改提供实时预览效果

import React, { useEffect, useState } from 'react';
import { Eye, EyeOff } from 'lucide-react';
import { BaseSetting } from '../../../types/settings';
import { useSettingsStore } from '../../../stores/settingsStore';

interface SettingPreviewProps {
  setting: BaseSetting;
  previewValue: any;
  onPreviewToggle?: (enabled: boolean) => void;
}

export const SettingPreview: React.FC<SettingPreviewProps> = ({
  setting,
  previewValue,
  onPreviewToggle
}) => {
  const [isPreviewEnabled, setIsPreviewEnabled] = useState(false);
  const [originalValue, setOriginalValue] = useState<any>(null);
  const { getSetting, setSetting } = useSettingsStore();

  // 切换预览状态
  const togglePreview = () => {
    const newPreviewState = !isPreviewEnabled;
    setIsPreviewEnabled(newPreviewState);
    
    if (newPreviewState) {
      // 启用预览：保存原始值并应用预览值
      const current = getSetting(setting.id);
      setOriginalValue(current);
      applyPreview(previewValue);
    } else {
      // 禁用预览：恢复原始值
      if (originalValue !== null) {
        applyPreview(originalValue);
        setOriginalValue(null);
      }
    }
    
    onPreviewToggle?.(newPreviewState);
  };

  // 应用预览效果
  const applyPreview = (value: any) => {
    // 根据设置类型应用不同的预览效果
    switch (setting.id) {
      case 'appearance.theme':
        applyThemePreview(value);
        break;
      case 'appearance.accentColor':
        applyAccentColorPreview(value);
        break;
      case 'editor.fontSize':
        applyFontSizePreview(value);
        break;
      case 'editor.fontFamily':
        applyFontFamilyPreview(value);
        break;
      case 'appearance.windowOpacity':
        applyOpacityPreview(value);
        break;
      default:
        // 对于其他设置，直接更新store
        setSetting(setting.id, value);
        break;
    }
  };

  // 主题预览
  const applyThemePreview = (theme: string) => {
    const root = document.documentElement;
    if (theme === 'auto') {
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      root.classList.toggle('dark', prefersDark);
    } else {
      root.classList.toggle('dark', theme === 'dark');
    }
  };

  // 强调色预览
  const applyAccentColorPreview = (color: string) => {
    const root = document.documentElement;
    root.style.setProperty('--accent-color', color);
  };

  // 字体大小预览
  const applyFontSizePreview = (fontSize: number) => {
    // 在编辑器预览区域应用字体大小
    const previewElements = document.querySelectorAll('.editor-preview');
    previewElements.forEach(element => {
      (element as HTMLElement).style.fontSize = `${fontSize}px`;
    });
  };

  // 字体系列预览
  const applyFontFamilyPreview = (fontFamily: string) => {
    // 在编辑器预览区域应用字体系列
    const previewElements = document.querySelectorAll('.editor-preview');
    previewElements.forEach(element => {
      (element as HTMLElement).style.fontFamily = fontFamily;
    });
  };

  // 透明度预览
  const applyOpacityPreview = (opacity: number) => {
    const root = document.documentElement;
    root.style.setProperty('--window-opacity', opacity.toString());
  };

  // 清理预览效果
  useEffect(() => {
    return () => {
      if (isPreviewEnabled && originalValue !== null) {
        applyPreview(originalValue);
      }
    };
  }, []);

  // 检查是否支持预览
  const supportsPreview = () => {
    const previewableSettings = [
      'appearance.theme',
      'appearance.accentColor',
      'editor.fontSize',
      'editor.fontFamily',
      'appearance.windowOpacity'
    ];
    return previewableSettings.includes(setting.id);
  };

  if (!supportsPreview()) {
    return null;
  }

  return (
    <div className="flex items-center space-x-2">
      <button
        onClick={togglePreview}
        className={`
          flex items-center space-x-1 px-2 py-1 text-xs rounded transition-colors
          ${isPreviewEnabled
            ? 'bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200'
            : 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-600'
          }
        `}
        title={isPreviewEnabled ? '禁用预览' : '启用预览'}
      >
        {isPreviewEnabled ? (
          <>
            <EyeOff className="w-3 h-3" />
            <span>预览中</span>
          </>
        ) : (
          <>
            <Eye className="w-3 h-3" />
            <span>预览</span>
          </>
        )}
      </button>
      
      {isPreviewEnabled && (
        <span className="text-xs text-blue-600 dark:text-blue-400">
          预览模式已启用
        </span>
      )}
    </div>
  );
};

// 编辑器预览组件
export const EditorPreview: React.FC<{
  fontSize?: number;
  fontFamily?: string;
  theme?: string;
}> = ({
  fontSize = 14,
  fontFamily = 'Consolas, "Courier New", monospace',
  theme = 'auto'
}) => {
  return (
    <div className="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
      <div className="bg-gray-100 dark:bg-gray-800 px-3 py-2 text-sm font-medium text-gray-700 dark:text-gray-300">
        编辑器预览
      </div>
      <div 
        className="editor-preview p-4 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 min-h-[120px]"
        style={{ 
          fontSize: `${fontSize}px`,
          fontFamily: fontFamily
        }}
      >
        <div className="text-gray-500 dark:text-gray-400 text-xs mb-2">1</div>
        <div className="text-blue-600 dark:text-blue-400">function</div>
        <div className="ml-4">
          <span className="text-purple-600 dark:text-purple-400">example</span>
          <span className="text-gray-900 dark:text-gray-100">(</span>
          <span className="text-orange-600 dark:text-orange-400">param</span>
          <span className="text-gray-900 dark:text-gray-100">) {'{'}</span>
        </div>
        <div className="ml-8">
          <span className="text-blue-600 dark:text-blue-400">return</span>
          <span className="text-green-600 dark:text-green-400"> "Hello, World!"</span>
          <span className="text-gray-900 dark:text-gray-100">;</span>
        </div>
        <div className="ml-4 text-gray-900 dark:text-gray-100">{'}'}</div>
      </div>
    </div>
  );
};

// 主题预览组件
export const ThemePreview: React.FC<{
  theme: string;
  accentColor?: string;
}> = ({
  theme,
  accentColor = '#007ACC'
}) => {
  const isDark = theme === 'dark' || (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches);
  
  return (
    <div className="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
      <div className="bg-gray-100 dark:bg-gray-800 px-3 py-2 text-sm font-medium text-gray-700 dark:text-gray-300">
        主题预览
      </div>
      <div className={`p-4 min-h-[120px] ${isDark ? 'bg-gray-900 text-white' : 'bg-white text-gray-900'}`}>
        <div className="flex items-center space-x-2 mb-3">
          <div 
            className="w-3 h-3 rounded-full"
            style={{ backgroundColor: accentColor }}
          />
          <span className="text-sm font-medium">示例界面</span>
        </div>
        <div className={`p-2 rounded ${isDark ? 'bg-gray-800' : 'bg-gray-100'}`}>
          <div className="text-sm mb-1">这是一个示例文本</div>
          <button 
            className="px-3 py-1 text-sm rounded text-white"
            style={{ backgroundColor: accentColor }}
          >
            按钮示例
          </button>
        </div>
      </div>
    </div>
  );
};
